<template>
  <div>
    <el-row :gutter="15">
      <el-form
        ref="elForm"
        :model="dataForm"
        :rules="dataRule"
        size="small"
        label-width="120px"
        label-position="right"
        :disabled="setting.readonly"
      >
        <template v-if="!loading && formOperates">
          <el-col :span="24" v-if="judgeShow('bookstarttime')">
            <el-form-item label="预订开始时间" prop="bookstarttime">
              <el-date-picker
                :disabled="judgeWrite('bookstarttime')"
                v-model="dataForm.bookstarttime"
                placeholder="请选择"
                clearable
                :style="{ width: '100%' }"
                type="datetime"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss"
                @change="getRoom()"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :span="24" v-if="judgeShow('bookendtime')">
            <el-form-item label="预订结束时间" prop="bookendtime">
              <el-date-picker
                :disabled="judgeWrite('bookendtime')"
                v-model="dataForm.bookendtime"
                placeholder="请选择"
                clearable
                :style="{ width: '100%' }"
                type="datetime"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss"
                @change="getRoom()"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :span="24" v-if="judgeShow('meetingroomid')">
            <el-form-item label="会议室名称" prop="meetingroomid">
              <el-select
                :disabled="judgeWrite('meetingroomid')"
                v-model="dataForm.meetingroomid"
                placeholder="请选择"
                clearable
                :style="{ width: '100%' }"
                filterable
              >
                <el-option
                  v-for="(item, index) in meetingroomidOptions"
                  :key="index"
                  :label="item.meetingroomname"
                  :value="item.id"
                  :disabled="item.disabled"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="24" v-if="judgeShow('bookdepartment')">
            <el-form-item label="预订部门" prop="bookdepartment">
              <dep-select
                :disabled="judgeWrite('bookdepartment')"
                v-model="dataForm.bookdepartment"
                placeholder="请选择"
                clearable
                filterable
              >
              </dep-select>
            </el-form-item>
          </el-col>

          <el-col :span="24" v-if="judgeShow('bookuserid')">
            <el-form-item label="预订人员" prop="bookuserid">
              <user-select
                :disabled="judgeWrite('bookuserid')"
                v-model="dataForm.bookuserid"
                placeholder="请选择"
                clearable
              >
              </user-select>
            </el-form-item>
          </el-col>

          <el-col :span="24" v-if="judgeShow('meetingusers')">
            <el-form-item label="参会人员" prop="meetingusers">
              <user-select
                :disabled="judgeWrite('meetingusers')"
                v-model="dataForm.meetingusers"
                placeholder="请选择"
                clearable
                :multiple="true"
              >
              </user-select>
            </el-form-item>
          </el-col>

          <el-col :span="24" v-if="judgeShow('meetingtheme')">
            <el-form-item label="会议主题" prop="meetingtheme">
              <el-input
                :disabled="judgeWrite('meetingtheme')"
                v-model="dataForm.meetingtheme"
                placeholder="请输入"
                clearable
                :style="{ width: '100%' }"
              >
              </el-input>
            </el-form-item>
          </el-col>
        </template>
      </el-form>
    </el-row>
    <UserBox v-if="userBoxVisible" ref="userBox" @submit="submit" />
  </div>
</template>
<script>
import request from "@/utils/request";
import { getDataInterfaceRes } from "@/api/systemData/dataInterface";
import { getDictionaryDataSelector } from "@/api/systemData/dictionary";
export default {
  components: {},
  props: [],
  data() {
    return {
      visible: false,
      loading: false,
      setting: {},
      eventType: "",
      userBoxVisible: false,
      dataForm: {
        id: "",
        flowId: "",
        status: 1,
        freeapproveruserid: "",
        bookstarttime: "",
        bookendtime: "",
        meetingroomid: "",
        bookdepartment: "",
        bookuserid: "",
        meetingusers: [],
        meetingtheme: "",
      },
      queryData: {
        id: undefined,
        start: undefined,
        end: undefined,
      },
      tableRequiredData: {},
      dataRule: {
        bookstarttime: [
          {
            required: true,
            message: "请选择",
            trigger: "change",
          },
        ],
        bookendtime: [
          {
            required: true,
            message: "请选择",
            trigger: "change",
          },
        ],
        meetingroomid: [
          {
            required: true,
            message: "请选择",
            trigger: "change",
          },
        ],
        bookdepartment: [
          {
            required: true,
            message: "请选择",
            trigger: "change",
          },
        ],
        bookuserid: [
          {
            required: true,
            message: "请选择",
            trigger: "click",
          },
        ],
        meetingusers: [
          {
            required: true,
            message: "请至少选择一个",
            trigger: "click",
          },
        ],
        meetingtheme: [
          {
            required: true,
            message: "请输入",
            trigger: "blur",
          },
        ],
      },
      meetingroomidOptions: [],
    };
  },
  computed: {
    formOperates() {
      return this.setting.formOperates;
    },
  },
  watch: {},
  created() {},
  mounted() {},
  methods: {
    judgeShow(id) {
      if (!this.setting.formOperates || !this.setting.formOperates.length)
        return true;
      let arr = this.setting.formOperates.filter((o) => o.id === id) || [];
      if (!arr.length) return true;
      let item = arr[0];
      return item.read;
    },
    judgeWrite(id) {
      if (!this.setting.formOperates || !this.setting.formOperates.length)
        return false;
      let arr = this.setting.formOperates.filter((o) => o.id === id) || [];
      if (!arr.length) return true;
      let item = arr[0];
      return !item.write;
    },
    goBack() {
      this.$emit("refresh");
    },

    getRoom() {
      (this.queryData.id = this.dataForm.id),
        (this.queryData.start = this.dataForm.bookstarttime),
        (this.queryData.end = this.dataForm.bookendtime);
      if (
        this.isDate(this.queryData.start) &&
        this.isDate(this.queryData.end)
      ) {
        console.log(this.queryData);
        request({
          url: `/api/example/BusMeetingRoomBook/getMeetingRoom/`,
          method: "post",
          data: this.queryData,
        }).then((res) => {
          if (res.data.length > 0) {
            this.meetingroomidOptions = res.data;
          }
        });
      }
    },
    isDate(date) {
      let start = date;
      var reg = /^[0-9,/:-\s]+$/;
      if (
        !isNaN(Date.parse(new Date(start.replace(/-/g, "/")))) &&
        isNaN(start) &&
        reg.test(start)
      ) {
        return true;
      }
    },
    init(data) {
      this.dataForm.id = data.id || "";
      this.setting = data;
      this.visible = true;
      this.updateDataRule();
      this.$nextTick(() => {
        this.$refs["elForm"].resetFields();
        if (this.dataForm.id) {
          console.log(111);
          this.loading = true;
          request({
            url: "/api/example/BusMeetingRoomBook/" + this.dataForm.id,
            method: "get",
          }).then((res) => {
            this.dataInfo(res.data);
            this.getRoom();
            this.loading = false;
          });
        }
        this.$emit("setPageLoad");
      });
      this.$store.commit("generator/UPDATE_RELATION_DATA", {});
    },
    updateDataRule() {
      let newRules = {};
      for (let i = 0; i < this.setting.formOperates.length; i++) {
        const item = this.setting.formOperates[i];
        if (!item.id.includes("-")) {
          const newRulesItem = {
            required: item.required,
            message: item.name + "不能为空",
            trigger: item.trigger || "blur",
          };
          if (!this.dataRule.hasOwnProperty(item.id)) {
            if (item.required) this.$set(newRules, item.id, [newRulesItem]);
          } else {
            let withoutRequiredItem = true;
            for (let i = 0; i < this.dataRule[item.id].length; i++) {
              if (this.dataRule[item.id][i].hasOwnProperty("required")) {
                this.dataRule[item.id][i].required = item.required;
                withoutRequiredItem = false;
              }
            }
            if (withoutRequiredItem && item.required)
              this.dataRule[item.id].push(newRulesItem);
          }
        } else {
          let key = item.id.split("-")[0];
          let newId = item.id.split("-")[1];
          let newItem = {
            ...item,
            id: newId,
          };
          if (!this.tableRequiredData.hasOwnProperty(key)) {
            this.$set(this.tableRequiredData, key, [newItem]);
          } else {
            this.tableRequiredData[key].push(newItem);
          }
        }
      }
      this.dataRule = { ...this.dataRule, ...newRules };
    },
    exist() {
      let isOk = true;
      for (let key in this.tableRequiredData) {
        if (this.dataForm[key] && Array.isArray(this.dataForm[key])) {
          for (let i = 0; i < this.dataForm[key].length; i++) {
            let item = this.dataForm[key][i];
            inner: for (let id in item) {
              let arr =
                this.tableRequiredData[key].filter((o) => o.id === id) || [];
              if (!arr.length) continue inner;
              if (arr[0].required) {
                let msg = `${arr[0].name}不能为空`;
                let boo = true;
                if (arr[0].dataType === "array") {
                  boo = !this.jnpf.isEmptyArray(item[id]);
                } else {
                  boo = !this.jnpf.isEmpty(item[id]);
                }
                if (!boo) {
                  this.$message({
                    message: msg,
                    type: "error",
                    duration: 1000,
                  });
                  isOk = false;
                  break;
                }
              }
            }
          }
        }
      }
      return isOk;
    },
    judgeRequired(id) {
      if (!this.formOperates || !this.formOperates.length) return false;
      let arr = this.formOperates.filter((o) => o.id === id) || [];
      if (!arr.length) return false;
      let item = arr[0];
      return item.required;
    },
    compare(date1, date2) {
      let start = new Date(date1);
      let end = new Date(date2);
      if (start > end) {
        return true;
      } else {
        return false;
      }
    },
    isOneDay(date1, date2) {
      let start = new Date(date1).setHours(0,0,0,0);
      let end = new Date(date2).setHours(0,0,0,0);
      console.log(start);
      console.log(end);
      if (start === end) {
        return false;
      } else {
        return true;
      }
    },
    // 表单提交
    dataFormSubmit(eventType) {
      this.$refs["elForm"].validate((valid) => {
        if (valid) {
          let start = this.dataForm.bookstarttime;
          let end = this.dataForm.bookendtime;
          if (Date.parse(start) < new Date()) {
            this.$message({
              showClose: true,
              message: "预订开始时间早于当前时间!",
              type: "error",
              duration: 1000,
            });
            return false;
          } else if (this.compare(start, end)) {
            this.$message({
              showClose: true,
              message: "结束时间早于开始时间!",
              type: "error",
              duration: 1000,
            });
            return false;
          } else if (this.isOneDay(start, end)) {
            this.$message({
              showClose: true,
              message: "开始时间和结束时间不在同一天!",
              type: "error",
              duration: 1000,
            });
            return false;
          }
          if (this.exist && !this.exist()) return;
          if (eventType === "audit" || eventType === "reject") {
            this.$emit("eventReceiver", this.dataForm, eventType);
            return;
          }
          this.dataForm.status = eventType === "submit" ? 0 : 1;
          this.dataForm.flowId = this.setting.flowId;
          this.eventType = eventType;
          if (this.eventType === "submit") {
            this.$confirm("您确定要提交当前流程吗, 是否继续?", "提示", {
              type: "warning",
            })
              .then(() => {
                this.request();
              })
              .catch(() => {});
          } else {
            this.request();
          }
        }
      });
    },
    request() {
      var _data = this.dataList();
      if (!this.dataForm.id) {
        request({
          url: "/api/example/BusMeetingRoomBook",
          method: "post",
          data: _data,
        }).then((res) => {
          this.$message({
            message: res.msg,
            type: "success",
            duration: 1000,
            onClose: () => {
              this.visible = false;
              this.$emit("close", true);
            },
          });
        });
      } else {
        request({
          url: "/api/example/BusMeetingRoomBook/" + this.dataForm.id,
          method: "PUT",
          data: _data,
        }).then((res) => {
          this.$message({
            message: res.msg,
            type: "success",
            duration: 1000,
            onClose: () => {
              this.visible = false;
              this.$emit("close", true);
            },
          });
        });
      }
    },
    dataList() {
      var _data = JSON.parse(JSON.stringify(this.dataForm));
      _data.meetingusers = JSON.stringify(_data.meetingusers);
      return _data;
    },
    dataInfo(dataAll) {
      let _dataAll = dataAll;
      _dataAll.meetingusers = JSON.parse(_dataAll.meetingusers);
      this.dataForm = _dataAll;
    },
  },
};
</script>
